<!-- src/views/ProfileUserView.vue -->
<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="title-left">个人中心</h1>
        <el-button class="back-home" type="text" @click="$router.push('/home')">返回首页</el-button>
      </div>
    </div>

    <div class="profile-content">
      <!-- 侧边栏导航 -->
      <div class="sidebar">
        <div class="user-info">
          <div class="avatar-wrapper" @click="triggerAvatarUpload">
            <el-avatar 
              :size="80" 
              :src="userAvatar" 
              icon="el-icon-user-solid" 
            />
            <div class="avatar-overlay">
              <i class="el-icon-camera"></i>
              <span>点击更换</span>
            </div>
          </div>
          <input 
            ref="avatarInput"
            type="file" 
            accept="image/*" 
            @change="handleAvatarUpload" 
            style="display: none;"
          />
          <h3 class="username">{{ userInfo.username }}</h3>
          <p class="welcome-text">欢迎来到全都有超市</p>
        </div>
        
        <el-menu
          :default-active="activeTab"
          class="profile-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="info">
            <i class="el-icon-user"></i>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="orders">
            <i class="el-icon-document"></i>
            <span>我的订单</span>
          </el-menu-item>
          <el-menu-item index="address">
            <i class="el-icon-location"></i>
            <span>收货地址</span>
          </el-menu-item>
          <el-menu-item index="cart">
            <i class="el-icon-shopping-cart-2"></i>
            <span>购物车</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区域 -->
      <div class="main-content">
        <!-- 个人信息 -->
        <div v-show="activeTab === 'info'" class="content-section">
          <div class="section-header">
            <h2>个人信息</h2>
          </div>
          <div class="info-content">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
              <el-descriptions-item label="订单数量">{{ userOrderCount }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- 我的订单 -->
        <div v-show="activeTab === 'orders'" class="content-section">
          <div class="section-header">
            <h2>我的订单</h2>
          </div>
          <div class="orders-content" ref="ordersContent">
            <el-table :data="sortedUserOrders" style="width: 100%" v-loading="loadingOrders">
              <el-table-column prop="id" label="订单号" width="180"></el-table-column>
              <el-table-column prop="date" label="下单时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.date) }}
                </template>
              </el-table-column>
              <el-table-column prop="total" label="订单金额">
                <template #default="scope">
                  ¥{{ scope.row.total }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getOrderStatusType(scope.row.status)">
                    {{ scope.row.status === 'completed' ? '已完成' : '未完成' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button size="small" @click="viewOrderDetail(scope.row)">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="ordersPage.currentPage"
                v-model:page-size="ordersPage.pageSize"
                :page-sizes="[5, 10, 20]"
                :total="userOrderCount"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>

        <!-- 收货地址 -->
        <div v-show="activeTab === 'address'" class="content-section">
          <div class="section-header">
            <h2>收货地址</h2>
            <el-button type="primary" @click="addAddress">新增地址</el-button>
          </div>
          <div class="address-content">
            <div class="address-container">
              <div class="address-list">
                <el-card 
                  v-for="(addr, index) in addressList" 
                  :key="index" 
                  class="address-card"
                  :class="{ 'selected': selectedAddressIndex === index }"
                  @click="selectAddress(index)"
                >
                  <div class="address-info">
                    <div class="address-main">
                      <p><strong>收货人:</strong> {{ addr.name }}</p>
                      <p><strong>联系电话:</strong> {{ addr.phone }}</p>
                      <p><strong>收货地址:</strong> {{ addr.detail }}</p>
                    </div>
                    <div class="address-actions">
                      <el-button size="small" @click.stop="editAddress(addr)">编辑</el-button>
                      <el-button size="small" type="danger" @click.stop="deleteAddress(index)">删除</el-button>
                    </div>
                  </div>
                </el-card>
                
                <!-- 当地址列表为空时显示提示 -->
                <div v-if="addressList.length === 0" class="empty-address">
                  <p>暂无收货地址</p>
                  <el-button type="primary" @click="addAddress">新增地址</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 购物车 -->
        <div v-show="activeTab === 'cart'" class="content-section">
          <div class="section-header">
            <h2>我的购物车</h2>
            <el-button type="primary" @click="$router.push('/cart')">查看购物车</el-button>
          </div>
          <div class="cart-content">
            <div v-if="userCartItems.length === 0" class="empty-cart">
              <p>购物车是空的</p>
              <el-button type="primary" @click="$router.push('/home')">去购物</el-button>
            </div>
            <div v-else class="cart-items">
              <el-table :data="userCartItems" style="width: 100%">
                <el-table-column label="商品">
                  <template #default="scope">
                    <div class="cart-item">
                      <img :src="scope.row.gImage" :alt="scope.row.gName" class="cart-item-image">
                      <span>{{ scope.row.gName }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="gPrice" label="单价" width="120">
                  <template #default="scope">
                    ¥{{ scope.row.gPrice }}
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="120">
                  <template #default="scope">
                    <el-input-number 
                      v-model="scope.row.quantity" 
                      :min="1" 
                      :max="99"
                      @change="updateQuantity(scope.row)" 
                      size="small"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="120">
                  <template #default="scope">
                    ¥{{ (scope.row.gPrice * scope.row.quantity).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="removeFromCart(scope.row.id)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="cart-summary">
                <div class="summary-item">
                  <span>商品总数: {{ userCartItemCount }}</span>
                </div>
                <div class="summary-item">
                  <span>总金额: <strong>¥{{ userCartTotal.toFixed(2) }}</strong></span>
                </div>
                <div class="summary-actions">
                  <el-button type="primary" @click="$router.push('/cart')">去结算</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 地址对话框 -->
    <el-dialog v-model="addressDialogVisible" :title="addressDialogTitle" width="500px">
      <el-form :model="currentAddress" label-width="80px">
        <el-form-item label="收货人">
          <el-input v-model="currentAddress.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="currentAddress.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="currentAddress.detail" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import defaultAvatar from '@/assets/images/user-avatar.jpg'

export default {
  name: 'ProfileUserView',
  data() {
    return {
      activeTab: 'info',
      ordersPage: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      addressList: [], 
      addressDialogVisible: false,
      addressDialogTitle: '',
      currentAddress: {
        name: '',
        phone: '',
        detail: ''
      },
      editingAddressIndex: -1,
      selectedAddressIndex: -1, 
      loadingOrders: false,
      scrollPosition: 0,
      userAvatar: defaultAvatar // 默认使用默认头像
    }
  },
  computed: {
    ...mapGetters([
      'getUserInfo', 
      'getOrders', 
      'cartItems', 
      'cartTotal', 
      'cartItemCount'
    ]),
    userInfo() {
      return this.getUserInfo || {}
    },
    currentUserOrders() {
      if (!this.userInfo.username) return []
      return this.getOrders.filter(order => order.username === this.userInfo.username)
    },

    sortedUserOrders() {
      const start = (this.ordersPage.currentPage - 1) * this.ordersPage.pageSize
      const end = start + this.ordersPage.pageSize
      
      const sortedOrders = [...this.currentUserOrders].sort((a, b) => {
        if (a.status === 'completed' && b.status !== 'completed') {
          return 1
        }
        if (a.status !== 'completed' && b.status === 'completed') {
          return -1
        }
        return new Date(b.date) - new Date(a.date)
      })
      
      return sortedOrders.slice(start, end)
    },
    userOrderCount() {
      return this.currentUserOrders.length || 0
    },
    userCartItems() {
      if (!this.userInfo.username) return []
      const userCartKey = `cart_${this.userInfo.username}`
      const userCart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
      return userCart
    },

    userCartTotal() {
      return this.userCartItems.reduce((total, item) => total + (item.gPrice * item.quantity), 0)
    },

    userCartItemCount() {
      return this.userCartItems.reduce((count, item) => count + item.quantity, 0)
    }
  },
  watch: {
    userInfo: {
      handler() {
        this.ordersPage.currentPage = 1
        this.loadAddressList()
        this.loadUserAvatar() // 加载用户头像
      },
      deep: true
    },

    $route(to, from) {
      if (from.name === '订单详情页名称' && to.name === 'Profile' && this.activeTab === 'orders') {
        this.$nextTick(() => {
          if (this.$refs.ordersContent) {
            this.$refs.ordersContent.scrollTop = this.scrollPosition
          }
        })
      }
    }
  },
  created() {
    this.loadAddressList()
    this.loadUserAvatar() // 加载用户头像
  },
  activated() {
    this.loadAddressList()
    this.loadUserAvatar() // 激活时重新加载头像
  },
  methods: {
    handleMenuSelect(key) {
      if (this.activeTab === 'orders' && this.$refs.ordersContent) {
        this.scrollPosition = this.$refs.ordersContent.scrollTop
      }
      
      this.activeTab = key

      if (key === 'orders') {
        this.$nextTick(() => {
          if (this.$refs.ordersContent) {
            this.$refs.ordersContent.scrollTop = this.scrollPosition
          }
        })
      }
    },
    goToEditProfile() {
      this.$message.info('用户资料编辑功能开发中')
    },
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    },
    getOrderStatusType(status) {
      if (status === 'completed') {
        return 'success'
      } else {
        return 'warning'
      }
    },
    viewOrderDetail(order) {
      if (this.$refs.ordersContent) {
        this.scrollPosition = this.$refs.ordersContent.scrollTop
      }
      
      this.$store.commit('SET_CURRENT_ORDER', order)
      this.$router.push('/order')
    },
    handleSizeChange(val) {
      this.ordersPage.pageSize = val
      this.ordersPage.currentPage = 1
    },
    handleCurrentChange(val) {
      this.ordersPage.currentPage = val
    },
    loadAddressList() {
      if (!this.userInfo.username) {
        this.addressList = []
        this.selectedAddressIndex = -1
        return
      }
      
      const userAddressKey = `addressList_${this.userInfo.username}`
      const savedAddressList = localStorage.getItem(userAddressKey)
      if (savedAddressList) {
        try {
          this.addressList = JSON.parse(savedAddressList)
        } catch (e) {
          console.error('解析地址列表失败:', e)
          this.addressList = []
        }
      } else {
        this.addressList = []
      }
      
      const userSelectedAddressKey = `selectedAddressIndex_${this.userInfo.username}`
      const savedSelectedIndex = localStorage.getItem(userSelectedAddressKey)
      if (savedSelectedIndex !== null && this.addressList.length > 0) {
        const index = parseInt(savedSelectedIndex)
        this.selectedAddressIndex = (index >= 0 && index < this.addressList.length) ? index : 0
      } else if (this.addressList.length > 0) {
        this.selectedAddressIndex = 0
        localStorage.setItem(userSelectedAddressKey, '0')
      } else {
        this.selectedAddressIndex = -1
      }
    },
    saveAddressList() {
      if (!this.userInfo.username) return
      const userAddressKey = `addressList_${this.userInfo.username}`
      localStorage.setItem(userAddressKey, JSON.stringify(this.addressList))
    },
    addAddress() {
      this.addressDialogTitle = '新增地址'
      
      this.currentAddress = {
        name: '',
        phone: '',
        detail: ''
      }
      
      this.editingAddressIndex = -1
      this.addressDialogVisible = true
    },
    editAddress(address) {
      this.addressDialogTitle = '编辑地址'
      this.currentAddress = { ...address }
      this.editingAddressIndex = this.addressList.indexOf(address)
      this.addressDialogVisible = true
    },
    saveAddress() {
      if (!this.currentAddress.name || !this.currentAddress.phone) {
        this.$message.warning('请填写收货人和联系电话')
        return
      }
      
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.currentAddress.phone)) {
        this.$message.warning('请输入正确的手机号码')
        return
      }
      
      if (this.editingAddressIndex === -1) {
        this.addressList.push({ ...this.currentAddress })
        if (this.addressList.length === 1) {
          this.selectedAddressIndex = 0
        }
      } else {
        this.addressList[this.editingAddressIndex] = { ...this.currentAddress }
      }
      
      this.saveAddressList()
      
      if (this.userInfo.username) {
        const userSelectedAddressKey = `selectedAddressIndex_${this.userInfo.username}`
        localStorage.setItem(userSelectedAddressKey, this.selectedAddressIndex.toString())
      }
      
      this.addressDialogVisible = false
      this.$message.success('地址保存成功')
    },
    deleteAddress(index) {
      this.$confirm('确定要删除这个地址吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addressList.splice(index, 1)
        this.saveAddressList()
        
        if (this.selectedAddressIndex === index) {
          this.selectedAddressIndex = this.addressList.length > 0 ? 0 : -1
          if (this.selectedAddressIndex >= 0 && this.userInfo.username) {
            const userSelectedAddressKey = `selectedAddressIndex_${this.userInfo.username}`
            localStorage.setItem(userSelectedAddressKey, this.selectedAddressIndex.toString())
          } else if (this.userInfo.username) {
            const userSelectedAddressKey = `selectedAddressIndex_${this.userInfo.username}`
            localStorage.removeItem(userSelectedAddressKey)
          }
        } else if (this.selectedAddressIndex > index) {
          this.selectedAddressIndex--
          if (this.userInfo.username) {
            const userSelectedAddressKey = `selectedAddressIndex_${this.userInfo.username}`
            localStorage.setItem(userSelectedAddressKey, this.selectedAddressIndex.toString())
          }
        }
        
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    updateQuantity(item) {
      const userCartKey = `cart_${this.userInfo.username}`
      let userCart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
      const cartItem = userCart.find(cartItem => cartItem.id === item.id)
      if (cartItem) {
        cartItem.quantity = item.quantity
        localStorage.setItem(userCartKey, JSON.stringify(userCart))
        if (item.quantity <= 0) {
          this.removeFromCart(item.id)
        }
      }
    },
    removeFromCart(itemId) {
      const userCartKey = `cart_${this.userInfo.username}`
      let userCart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
      userCart = userCart.filter(item => item.id !== itemId)
      localStorage.setItem(userCartKey, JSON.stringify(userCart))
      this.$message.success('商品已从购物车中移除')
    },
    selectAddress(index) {
      this.selectedAddressIndex = index
      if (this.userInfo.username) {
        const userSelectedAddressKey = `selectedAddressIndex_${this.userInfo.username}`
        localStorage.setItem(userSelectedAddressKey, index.toString())
      }
    },
    
    // 头像相关方法
    triggerAvatarUpload() {
      this.$refs.avatarInput.click()
    },
    
    handleAvatarUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.$message.error('请选择图片文件')
        return
      }
      
      // 验证文件大小 (限制为2MB)
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('图片大小不能超过2MB')
        return
      }
      
      const reader = new FileReader()
      reader.onload = (e) => {
        const avatarData = e.target.result
        this.userAvatar = avatarData
        this.saveUserAvatar(avatarData)
        this.$message.success('头像更新成功')
      }
      reader.readAsDataURL(file)
    },
    
    saveUserAvatar(avatarData) {
      if (!this.userInfo.username) return
      const userAvatarKey = `avatar_${this.userInfo.username}`
      localStorage.setItem(userAvatarKey, avatarData)
    },
    
    loadUserAvatar() {
      if (!this.userInfo.username) {
        this.userAvatar = defaultAvatar
        return
      }
      
      const userAvatarKey = `avatar_${this.userInfo.username}`
      const savedAvatar = localStorage.getItem(userAvatarKey)
      this.userAvatar = savedAvatar || defaultAvatar
    }
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f0f9f0;
  min-height: calc(100vh - 120px);
}

.page-header {
  background: linear-gradient(to right, #4caf50, #8bc34a); 
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-left {
  color: white;
  margin: 0;
  font-size: 24px;
  text-align: left;
}

.back-home {
  color: white;
  font-size: 16px;
  padding: 0;
}

.back-home:hover {
  color: #e0f7fa;
}

.profile-content {
  display: flex;
  gap: 20px;
}

.sidebar {
  width: 250px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.user-info {
  padding: 30px 20px;
  text-align: center;
  background: linear-gradient(135deg, #00c853, #64dd17); 
  color: white;
  position: relative;
}

.avatar-wrapper {
  margin-bottom: 15px;
  cursor: pointer;
  position: relative;
  display: inline-block;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 80px;
  height: 80px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay i {
  font-size: 20px;
  margin-bottom: 5px;
}

.username {
  margin: 10px 0 5px;
  font-size: 18px;
  font-weight: normal;
}

.welcome-text {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.profile-menu {
  border: none;
}

.profile-menu .el-menu-item {
  height: 50px;
  line-height: 50px;
}

.profile-menu .el-menu-item i {
  margin-right: 10px;
  color: #00c853;
}

.profile-menu .el-menu-item.is-active {
  background-color: #e8f5e9;
  color: #00c853;
  border-right: 3px solid #00c853;
}

.main-content {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e8f5e9;
}

.section-header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.content-section {
  min-height: 500px;
}

.info-content {
  padding: 20px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.orders-content {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.address-content {
  padding: 20px;
  position: relative;
  display: flex;
  flex-direction: column; 
}

.address-container {
  display: flex;
  flex-direction: column;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  flex-grow: 1; 
}

.address-card {
  border: 1px solid #e8f5e9;
  border-radius: 4px;
}

.address-card.selected {
  background-color: #e8f5e9;
  border-color: #4caf50; 
}

.address-info {
  display: flex;
  justify-content: space-between;
}

.address-main p {
  margin: 8px 0;
}

.address-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.empty-address {
  text-align: center;
  padding: 50px 0;
  grid-column: 1 / -1;
}

.empty-address p {
  font-size: 18px;
  margin-bottom: 20px;
  color: #999;
}

.cart-content {
  padding: 20px;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
}

.empty-cart p {
  font-size: 18px;
  margin-bottom: 20px;
  color: #999;
}

.cart-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-item-image {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.cart-summary {
  margin-top: 20px;
  padding: 20px;
  background: #e8f5e9;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-item {
  font-size: 16px;
}

.summary-item strong {
  color: #4caf50;
  font-size: 18px;
}

.summary-actions {
  margin-left: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* Element UI 组件样式定制 */
:deep(.el-descriptions__label) {
  background-color: #e8f5e9 !important;
  width: 100px;
}

:deep(.el-table th) {
  background-color: #e8f5e9 !important;
}

:deep(.el-table tr:hover) {
  background-color: #f1f9f1 !important;
}

:deep(.el-button--primary) {
  background-color: #4caf50;
  border-color: #4caf50;
}

:deep(.el-button--primary:hover) {
  background-color: #43a047;
  border-color: #43a047;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
  }
  
  .address-list {
    grid-template-columns: 1fr;
  }
  
  .cart-summary {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .summary-actions {
    margin-left: 0;
  }
}
</style>